const fs = require('fs')
const { resolve } = require('path')
const cheerio = require('cheerio')

const getNav = (html) => {
	const $ = cheerio.load(html)
	const $div = $('<div></div>')
	$('h2').eq(0).addClass('active')
	$('h2, h3').each(function (index, item) {
		let $item = $(item)
		let $a = $("<a></a>")
		let href = '#' + $item.attr('id')
		$item.removeAttr('id')
		$a.attr('href', href)
		$a.html($item.text())
		$item.html($a)
	})

	$('h2, h3').appendTo($div)
	return $div.html()
}

const getBody = (html) => {
	const $ = cheerio.load(html)
	return $('body').html()
}

function readFileAsync(path) {
	return new Promise(function (resolve) {
		fs.readFile(path, {encoding:'utf8', flag:'r'}, function (err, result) {
			if (err) {
				console.log(err)
			} else {
				resolve(result)	
			}
		})
	})
}

exports.getCourses = async (courseid, chepterid) => {
	let prefix = './public/html/'
  const pages = require(resolve(prefix, `${courseid}/config.js`))
	let data = {}
	if (chepterid) {
    const result = await readFileAsync(resolve(prefix, `${courseid}/${chepterid}.html`))
    
		data = {
			pages: pages.pages,
			topic: pages.topic,
			nav: getNav(result),
			body: getBody(result)
		}

	} else {
		data = {
			...pages
		}
	}

  return data
}



